package com.opticon.vaadinR.core;

import com.google.common.io.Files;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * This class is a File Wrapper for a R source script.
 */
public class RSource {
    private static Logger logger = Logger.getLogger(RSource.class);

    /**
     * The R-source file.
     */
    private ArrayList<String> iContent = null;

    /**
     * This file references a R src script file that can be executed.
     *
     * @param aFile Src File to be run by R.
     */
    public RSource(File aFile) {
        try {
            List<String> lineList = Files.readLines(aFile, Charset.defaultCharset());
            iContent = new ArrayList<String>(lineList);

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * Returns the src file as a single string.
     *
     * @return String
     */
    public String getCode() {
        StringBuffer sb = new StringBuffer();
        for (String line : iContent) {
            // skip comment lines.
            if(line.length() > 0 && line.charAt(0) != '#'){
                sb.append(line);
                sb.append("\n");
            }
        }
        return sb.toString();
    }

    /**
     * Filters the R-source file content by the specified filter.
     *
     * @param aFilter RFilter instance with Key/Values to be filtered.
     */
    public void filter(RFilter aFilter) {
        String oldLine = null;
        String filteredLine = null;

        for (int i = 0; i < iContent.size(); i++) {
            oldLine = iContent.get(i);
            // apply the filter.
            filteredLine = aFilter.filter(oldLine);
            // reset to the file.
            iContent.set(i, filteredLine);
        }
    }


}
